package com.stock.stockana.ui.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.stock.publiclib.utils.StringUtil;
import com.stock.stockana.R;
import com.stock.stockana.StockCenter;
import com.stock.stockana.beans.StockInfoBean;
import com.stock.stockana.constants.NetWorkConstants;
import com.stock.stockana.events.StockListChangedEvent;
import com.stock.stockana.events.network.GetAllStocksEvent;
import com.stock.stockana.requests.GetAllStocks;
import com.stock.stockana.ui.activities.MainActivity;
import com.stock.stockana.ui.activities.StockDetailActivity;
import com.stock.stockana.ui.adapter.SearchedStockAdapter;
import com.stock.stockana.ui.adapter.StockListAdapter;
import com.stock.stockana.ui.listener.OnStockItemClickedListener;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

/**
 * ---------------------------------------------------
 * Description:
 * Author: ljgsonx
 * Belong to: com.stock.stockana.fragments
 * Time: 2016/1/20 17:34
 * ---------------------------------------------------
 */
public class StockListFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{

    private final static String TAG = "StockListFragment--->";
    private View mView;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView mRecyclerView;
    private RecyclerView.LayoutManager mLayoutManager;
    private StockListAdapter mStockListAdapter;
    private SearchedStockAdapter mSearchedStockAdapter;
    private boolean firstIn = true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.frag_main, container, false);
        return mView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mSwipeRefreshLayout = (SwipeRefreshLayout) mView.findViewById(com.stock.publiclib.R.id.id_swiperefreshlayout);
        mRecyclerView = (RecyclerView) mView.findViewById(com.stock.publiclib.R.id.id_recyclerview);

        // 刷新时，指示器旋转后变化的颜色
        mSwipeRefreshLayout.setColorSchemeResources(com.stock.publiclib.R.color.main_blue_light, com.stock.publiclib.R.color.main_blue_dark);
        mSwipeRefreshLayout.setOnRefreshListener(this);

        mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);

        mStockListAdapter = new StockListAdapter(getContext());
        mStockListAdapter.setOnStockItemClickedListener(new OnStockItemClickedListener() {
            @Override
            public void onStockItemCliked(StockInfoBean clickedStock) {
                Intent intent = new Intent(getActivity(), StockDetailActivity.class);
                intent.putExtra("clickedStock", clickedStock);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
            }
        });
//        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(mStockListAdapter);
//        alphaAdapter.setDuration(2000);
//        alphaAdapter.setInterpolator(new OvershootInterpolator());
//        alphaAdapter.setFirstOnly(false);
//        mRecyclerView.setAdapter(alphaAdapter);
        mRecyclerView.setAdapter(mStockListAdapter);
        mRecyclerView.setLayoutManager(mLayoutManager);
    }

    private void getData() {
        StockCenter.doReq(GetAllStocks.build());
    }

    @Override
    public void onRefresh() {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getData();
            }
        }, 100);
    }

    /**
     * Description: 所有收藏股票的数据获取到之后,通知各个页面
     * Author: ljgsonx
     * Time: 2016/1/23 18:57
     */
    @Subscribe
    public void onEventMainThread(GetAllStocksEvent event){
        mSwipeRefreshLayout.setRefreshing(false);
        ((MainActivity)getActivity()).stopPopLoading();
        if(event.getResponseCode() == NetWorkConstants.RESPONSE_CODE_OK) {
            //通知要打开的股票详情页
            Bundle bundle = getArguments();
            if (bundle != null) {
                String pushedStockNum = bundle.getString("pushedStockNum");
                if (!StringUtil.isBlank(pushedStockNum)) {
                    for (StockInfoBean sb : GetAllStocks.stocks) {
                        if (pushedStockNum.equals(sb.getStNum())) {
                            ((MainActivity) getActivity()).showPushedStockIfNeed(sb);
                            break;
                        }
                    }
                }
            }
            //通知本页面,股票搜索页面,查看叫醒页面
            EventBus.getDefault().post(new StockListChangedEvent());
        }else {
            Log.d(TAG, event.getMessage());
            Toast.makeText(getActivity(), NetWorkConstants.RESPONSE_COMMON_MESSAGE, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Description: 自选列表产生变化,刷新适配器
     * Author: ljgsonx
     * Time: 2016/1/23 18:57
     */
    @Subscribe
    public void onEventMainThread(StockListChangedEvent event){
        mStockListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        if(firstIn){
            getData();
            mSwipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(true);
                }
            });
            firstIn = false;
        }
    }
}
